package com.yanqu.road.server.manager.player;

import com.yanqu.road.entity.player.CrossUserBaseInfo;
import com.yanqu.road.entity.player.UserBaseInfo;
import com.yanqu.road.entity.union.cross.CrossUnionMember;
import com.yanqu.road.logic.pb.PlayerBasePb;
import com.yanqu.road.message.YanQuMessage;
import com.yanqu.road.pb.cross.group.CrossGroupProto;
import com.yanqu.road.pb.union.cross.CrossUnionProto;
import com.yanqu.road.pb.worldmessage.WorldMessageProto;
import com.yanqu.road.server.TempMgr;
import com.yanqu.road.server.logic.MessageHelper;
import com.yanqu.road.server.manager.union.CrossUnionMgr;
import com.yanqu.road.server.manger.UnionHuaBenServerGroupMgr;
import com.yanqu.road.server.protocol.Protocol;
import com.yanqu.road.utils.YanQuMessageUtils;
import com.yanqu.road.utils.string.StringUtils;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

public class WorldMessageMgr extends TempMgr {

    private static Map<String, List<WorldMessageProto.WorldMessageTempMsg.Builder>> unionMessageMsgMap;

    public static final String SEPARATOR = "&#!";

    public static final int MAX_MESSAGE_COUNT = 50;

    @Override
    public boolean init() throws Exception {
        return reload();
    }

    @Override
    public boolean reloadConfig() throws Exception {
        return true;
    }

    @Override
    public boolean reloadData() throws Exception {

        unionMessageMsgMap = new ConcurrentHashMap<>();
        return true;
    }

    @Override
    public boolean stop() {
        return true;
    }

    public static List<WorldMessageProto.WorldMessageTempMsg.Builder> getUnionMessageMsgList(String unionUid){
        if(!StringUtils.isNullOrEmpty(unionUid)){
            List<WorldMessageProto.WorldMessageTempMsg.Builder> dataList = unionMessageMsgMap.get(unionUid);
            if(null != dataList){
                return new ArrayList<>(dataList);
            }
        }
        return null;
    }

    public static void changeUnionChatMessage(long sendUserId, int type, String content, long startTime, String unionUid) {
        synchronized (unionMessageMsgMap) {
            List<WorldMessageProto.WorldMessageTempMsg.Builder> builders = unionMessageMsgMap.get(unionUid);
            if (builders != null) {
                for (WorldMessageProto.WorldMessageTempMsg.Builder builder : builders) {
                    if (builder.getType() == type && builder.getUserId() == sendUserId && builder.getSendTime() > startTime / 1000) {
                        builder.setContent(content);
                    }
                }
            }
        }
    }

    public static void sendUnionChat(long serverId, long playerId, WorldMessageProto.WorldMessageTempMsg.Builder msg, String unionUid) {

        synchronized (unionMessageMsgMap){
            if(!unionMessageMsgMap.containsKey(unionUid)){
                unionMessageMsgMap.put(unionUid, new ArrayList<>());
            }
            List<WorldMessageProto.WorldMessageTempMsg.Builder> unionMsgList = unionMessageMsgMap.get(unionUid);
            if(unionMsgList.size() >= MAX_MESSAGE_COUNT){
                unionMsgList.remove(0);
            }
            unionMsgList.add(msg);
        }
        syncServerMsg(unionUid, msg);
    }

    private static void syncServerMsg(String unionUid, WorldMessageProto.WorldMessageTempMsg.Builder msg) {
        Map<Long, List<Long>> serverUserMap = new HashMap<>();
        Map<Long, CrossUnionMember> memberMap = CrossUnionMgr.getUnionMemberMap(unionUid);
        if(memberMap != null){
            for (Map.Entry<Long, CrossUnionMember> entry : memberMap.entrySet()) {
                CrossUnionMember member = entry.getValue();
                if(serverUserMap.get(member.getServerId()) == null){
                    serverUserMap.put(member.getServerId(), new ArrayList<>());
                }
                serverUserMap.get(member.getServerId()).add(entry.getKey());
            }
        }

        for (Map.Entry<Long, List<Long>> entry : serverUserMap.entrySet()) {
            CrossUnionProto.UnionMemberChatSyncMsg.Builder syncMsg = CrossUnionProto.UnionMemberChatSyncMsg.newBuilder();
            syncMsg.setMsg(msg);
            syncMsg.addAllUserId(entry.getValue());
            MessageHelper.sendPacket(entry.getKey(), 0, YanQuMessageUtils.buildMessage(Protocol.A_CROSS_UNION_MEMBER_MESSAGE_PUSH, syncMsg));
        }
    }

    public static void sendSystemGroupChat(long serverId, long playerId, WorldMessageProto.WorldMessageTempMsg.Builder msg, int systemId){
        int groupId = UnionHuaBenServerGroupMgr.getGroupIdByServerId(serverId);
        CrossGroupProto.SystemCrossGroupChatReqMsg.Builder reqMsg = CrossGroupProto.SystemCrossGroupChatReqMsg.newBuilder();
        reqMsg.setGroupId(groupId);
        reqMsg.setSystemId(systemId);
        reqMsg.setMsg(msg);
        YanQuMessage pbMsg = YanQuMessageUtils.buildMessage(Protocol.C_SYSTEM_GROUP_CHAT, reqMsg);
        MessageHelper.sendPacket(serverId, playerId, pbMsg);
    }

    public static String encodeContent(Object ... strings) {
        StringBuilder content = new StringBuilder();
        if (strings != null) {
            for (Object str : strings) {
                content.append(str).append(SEPARATOR);
            }
        }
        if(content.length() > 0){
            return content.substring(0, content.length() - SEPARATOR.length());
        }
        return content.toString();
    }

    public static WorldMessageProto.WorldMessageTempMsg.Builder parseWorldMessageTempMsg(CrossUserBaseInfo userInfo, int type, int contentType, String content, long nowTime,
                                                                                         int activityId, String banquetId) {
        WorldMessageProto.WorldMessageTempMsg.Builder msg = WorldMessageProto.WorldMessageTempMsg.newBuilder();
        msg.setType(type);
        msg.setContentType(contentType);
        if (content != null) {
            msg.setContent(content);
        }

        msg.setSendTime(nowTime / 1000);
        msg.setUserId(userInfo.getUserId());
        msg.setPlayerBaseData(PlayerBasePb.parsePlayerBaseTempMsg(userInfo.getUserBaseInfo()));
        msg.setActivityId(activityId);
        if (banquetId != null) {
            msg.setBanquetId(banquetId);
        }
        //msg.setIsInstructor(userInfo.isInstructor());
        return msg;
    }

    public static WorldMessageProto.WorldMessageTempMsg.Builder parseWorldMessageTempMsg(UserBaseInfo userInfo, long userId, int type, int contentType, String content, long nowTime,
                                                                                         int activityId, String banquetId) {
        WorldMessageProto.WorldMessageTempMsg.Builder msg = WorldMessageProto.WorldMessageTempMsg.newBuilder();
        msg.setType(type);
        msg.setContentType(contentType);
        if (content != null) {
            msg.setContent(content);
        }

        msg.setSendTime(nowTime / 1000);
        msg.setUserId(userId);
        msg.setPlayerBaseData(PlayerBasePb.parsePlayerBaseTempMsg(userInfo));
        msg.setActivityId(activityId);
        if (banquetId != null) {
            msg.setBanquetId(banquetId);
        }
        //msg.setIsInstructor(userInfo.isInstructor());
        return msg;
    }
}
